﻿using log4net;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using WMSSyncData.DAL;
using WMSSyncData.DAL.Oracle;
using WMSSyncData.DAL.SqlDB;
using WMSSyncData.Model.WMSModel;
using WMSSyncData.Utils;

namespace WMSSyncData.Core
{
    public class SyncERPData
    {

        private readonly ILog _logger = LogManager.GetLogger(typeof(SyncERPData));
        public void SyncOutStockData()
        {
            Tddev111DAL tddev111DAL = new Tddev111DAL();
            DAL.Oracle.WMS_T_OutStockRowsDAL wMS_T_OutStockRowsDAL = new DAL.Oracle.WMS_T_OutStockRowsDAL();

            var list = tddev111DAL.GetAll();
            if (list.Count > 0)
            {
                list = list.Where(x => !x.RelatedBill.StartsWith("VMB")).ToList();

                var rowsList = wMS_T_OutStockRowsDAL.GetAll();
                var cloneList = Clone(rowsList);

                ///VMB的出库数据写入出库表
                rowsList = rowsList.Where(x => !x.BillNo.StartsWith("VMB")).ToList();

                var execRes = 0;
                if (list.Count > 0)
                {
                    execRes = new BaseSqlDBDAL<WMS_T_OutStock>().InsertBatch(list);
                }

                var addRowsList = FormatRowsList(rowsList, list);
                var execRowsRes = 0;
                var updateBillTypeRes = 0;
                if (addRowsList.Count > 0)
                {
                    execRowsRes = new BaseSqlDBDAL<WMS_T_OutStockRows>().InsertBatch(addRowsList);
                    OutStockMDAL outStockMDAL = new OutStockMDAL();
                    updateBillTypeRes = outStockMDAL.UpdateBillTypeForVMI();
                }

                if (cloneList.Count > 0)
                {
                    var resultclone = wMS_T_OutStockRowsDAL.UpdateHost(cloneList);
                    if (resultclone > 0)
                    {
                        //_logger.Info("Clone修改成功!XXXXX");
                    }
                    else
                    {
                        //_logger.Info("Clone修改失败！XXXXXX");
                    }
                }
            }

            SyncChangeData();
        }

        public void SyncChangeData()
        {
            Tddev111DAL tddev111DAL = new Tddev111DAL();
            var wMS_T_OutStockRowsDAL = new DAL.SqlDB.WMS_T_OutStockRowsDAL();
            var dt = tddev111DAL.GetChangeDT();
            var updateDt = dt.Clone();
            var noUpdateDt = dt.Clone();
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    var relationBill = dr["RelatedBill"].ToString();
                    var sn = dr["SN"].ToString();
                    var rowNo = dr["RowNo"].ToString();
                    var status = dr["Status"].ToString();
                    var item = wMS_T_OutStockRowsDAL.Get(relationBill, sn, rowNo);
                    var planQty = dr["PlanQty"].ToString().ToInt32();
                    var remark = dr["Remark"].ToString();

                    if (item != null)
                    {
                        var res = false;
                        if (status.EqualsOrdinalIgnoreCase("2"))//修改，修改对应的数量
                        {
                            res = wMS_T_OutStockRowsDAL.UpdateOutStockRowsPlanQty(item.BillNo, planQty, remark);
                        }
                        else if (status.EqualsOrdinalIgnoreCase("3"))//删除，我们这边把OutStock状态修改为D
                        {
                            res = wMS_T_OutStockRowsDAL.UpdateOutStockStatus(item.BillNo);
                        }
                        if (res)
                        {
                            updateDt.Clear();
                            updateDt.Rows.Add(dr.ItemArray);
                            tddev111DAL.UpdateStatus(updateDt);
                        }
                    }
                    else//同步过来的订单已经进行了操作，则不修改
                    {
                        noUpdateDt.Clear();
                        noUpdateDt.Rows.Add(dr.ItemArray);
                        tddev111DAL.UpdateText(noUpdateDt);
                    }
                }

                //if (updateDt.Rows.Count > 0)
                //{
                //    tddev111DAL.UpdateStatus(updateDt);
                //}

                //if (noUpdateDt.Rows.Count > 0)
                //{
                //    tddev111DAL.UpdateText(noUpdateDt);
                //}

            }

        }


        public List<WMS_T_OutStock> FormatList(List<WMS_T_OutStock> list)
        {
            var result = new List<WMS_T_OutStock>();

            var date = DateTime.Now;
            var temp = "B0101" + date.ToString("yyyyMMddHHmmss");
            int num = 0;
            foreach (var item in list)
            {
                if (num >= 9999)
                {
                    num = 0;
                    date = DateTime.Now;
                    temp = "B0101" + date.ToString("yyyyMMddHHmmss");
                }
                var billNo = temp + String.Format("{0:0000}", num);
                item.BillNo = billNo;
                item.Guid = Guid.NewGuid().ToString();
                result.Add(item);
                num++;
            }
            return result;
        }

        public List<WMS_T_OutStockRows> FormatRowsList(List<WMS_T_OutStockRows> rowsList, List<WMS_T_OutStock> list)
        {
            var result = new List<WMS_T_OutStockRows>();
            foreach (var item in rowsList)
            {
                //从Oracle数据库获取ROWS数据的时候，把RelationBill放到了BillNO字段上面，现在通过这个字段关联，获取真正的BillNO
                var searchItem = list.Where(x => x.RelatedBill.EqualsOrdinalIgnoreCase(item.BillNo)
                && x.SN == item.SN && x.RowNo == item.RowNo).FirstOrDefault();
                if (searchItem != null)
                {
                    item.BillNo = searchItem.BillNo;
                    result.Add(item);
                }
            }
            return result;
        }

        public static T Clone<T>(T RealObject)
        {
            using (Stream objectStream = new MemoryStream())
            {
                //利用 System.Runtime.Serialization序列化与反序列化完成引用对象的复制  
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, RealObject);
                objectStream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(objectStream);
            }
        }
        public void SyncInStockMData()
        {
            WMS_M_InStockDAL wMS_M_InStockDAL = new WMS_M_InStockDAL();
            WMS_T_InStockRowsDAL wMS_T_InStockRowsDAL = new WMS_T_InStockRowsDAL();
            WMS_M_InStockDetails wMS_M_InStockDetails = new WMS_M_InStockDetails();

            var list = wMS_M_InStockDAL.GetSyncData();

            if (list.Count > 0)
            {
                var rowsList = wMS_T_InStockRowsDAL.GetSyncData();
                var detailsList = wMS_M_InStockDetails.GetSyncData();
                //var inventoryDT = wMS_M_InStockDAL.GetInventoryInfo("半成品入库");
                //var inventoryRes = InsertInventoryDT(inventoryDT);
                var ret = wMS_T_InStockRowsDAL.UpdateStatus(rowsList);

                if (ret > 0)
                {
                    var result = new BaseSqlDBDAL<WMS_T_InStock>().InsertBatch(list);
                    ret = wMS_M_InStockDetails.UpdateStatus(detailsList);
                }

                if (ret > 0)
                {
                    //var result = new BaseSqlDBDAL<WMS_T_InStock>().InsertBatch(list);
                    var rowsResult = new BaseSqlDBDAL<WMS_T_InStockRows>().InsertBatch(rowsList);

                    var detailsResult = 0;
                    if (detailsList.Count > 0)
                    {
                        detailsResult = new BaseSqlDBDAL<WMS_T_InstockRowDetails>().InsertBatch(detailsList);
                    }
                }

            }
            CombineBoxNo();
        }
        //public void SyncInStockMData()
        //{
        //    WMS_M_InStockDAL wMS_M_InStockDAL = new WMS_M_InStockDAL();
        //    WMS_T_InStockRowsDAL wMS_T_InStockRowsDAL = new WMS_T_InStockRowsDAL();
        //    WMS_M_InStockDetails wMS_M_InStockDetails = new WMS_M_InStockDetails();


        //    var listall = wMS_M_InStockDAL.GetT();
        //    if (listall!=null&&listall.Rows.Count>0)
        //    {
        //        var result = 0;
        //        var list = wMS_M_InStockDAL.GetSyncData("成品入库");
        //        var rowsList = wMS_T_InStockRowsDAL.GetSyncData();
        //        var detailsList = wMS_M_InStockDetails.GetSyncData();
        //        var inventoryDT = wMS_M_InStockDAL.GetInventoryInfo("半成品入库");
        //        List<WMS_T_InStock> listwIS = new List<WMS_T_InStock>(); 
        //        if (inventoryDT != null) {

        //            //取重复
        //            var distinctTable = inventoryDT.Clone();
        //            //DataView dv = new DataView(inventoryDT);
        //            //distinctTable = dv.ToTable(true, new string[]{ "BillNO" });
        //            distinctTable = inventoryDT.AsEnumerable().Cast<DataRow>().GroupBy(p => p.Field<string>("BillNO")).Select(p => p.FirstOrDefault()).CopyToDataTable();
        //            // 生成需要输入的对象
        //            foreach (DataRow dr in distinctTable.Rows)
        //            {
        //                WMS_T_InStock InStockEntity = new WMS_T_InStock();
        //                InStockEntity.Guid = Guid.NewGuid().ToString();
        //                InStockEntity.BillNo = dr["BillNO"].ToString();
        //                InStockEntity.RelatedBill = dr["RelatedBill"] ==null?"": dr["RelatedBill"].ToString();
        //                InStockEntity.Status = "1";  //半成品入库后直接同步到ERP
        //                InStockEntity.BillType = "半成品入库";
        //                InStockEntity.Storage_SN = dr["Storage_SN"].ToString();
        //                InStockEntity.Creator = dr["creator"].ToString();
        //                InStockEntity.CreateTime =Convert.ToDateTime(dr["CreateTime"].ToString());
        //                listwIS.Add(InStockEntity);
        //            }
        //            result=  new BaseSqlDBDAL<WMS_T_InStock>().InsertBatch(listwIS);

        //        }

        //        if (list != null&&list.Count>0)
        //        { 
        //               result = new BaseSqlDBDAL<WMS_T_InStock>().InsertBatch(list);
        //        }
        //        var rowsResult = new BaseSqlDBDAL<WMS_T_InStockRows>().InsertBatch(rowsList);


        //        var detailsResult = 0;
        //        if (detailsList.Count > 0)
        //        {
        //            detailsResult = new BaseSqlDBDAL<WMS_T_InstockRowDetails>().InsertBatch(detailsList);
        //        }

        //        var inventoryRes = InsertInventoryDT(inventoryDT);

        //        if (result > 0)
        //        {
        //            wMS_T_InStockRowsDAL.UpdateStatus(rowsList);
        //        }

        //        if (detailsResult > 0)
        //        {
        //            wMS_M_InStockDetails.UpdateStatus(detailsList);
        //        }
        //    }
        //    CombineBoxNo();
        //}

        public void CombineBoxNo()
        {
            WMS_T_InStorckRowDetailsDAL dal = new WMS_T_InStorckRowDetailsDAL();

            var list = dal.GetSameBoxNoAndBillNo();

            if (list.Count > 0)
            {
                var insertList = new List<WMS_T_InstockRowDetails>();

                var boxNoList = list.Select(x => x.BoxNo).Distinct();

                foreach (var item in boxNoList)
                {
                    var searchList = list.Where(x => x.BoxNo.EqualsOrdinalIgnoreCase(item));
                    var qty = searchList.Sum(x => x.PutawayQty);
                    var searchItem = searchList.FirstOrDefault();

                    var insertItem = new WMS_T_InstockRowDetails()
                    {
                        Guid = Guid.NewGuid().ToString(),
                        PartNumber = searchItem.PartNumber,
                        Version = searchItem.Version,
                        DateCode = searchItem.DateCode,
                        LotNo = searchItem.LotNo,
                        BoxNo = item,
                        Creator = "WMSSync",
                        CreateTime = DateTime.Now,
                        Status = "0",
                        PutawayQty = qty,
                        RealQty = qty,
                        Barcode = searchItem.Barcode,
                        Uint = searchItem.Uint
                    };
                    insertList.Add(insertItem);
                }

                var updateStatus = dal.UpdateSameBoxNoStatus(list);

                if (updateStatus)
                {
                    dal.InsertBatch(insertList);
                }

            }
        }

        public bool InsertInventoryDT(DataTable dt)
        {
            var result = false;

            try
            {
                var inventoryList = new List<WMS_T_Inventory>();
                var inventoryHisList = new List<WMS_T_InventoryHistory>();
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        var inventory = new WMS_T_Inventory()
                        {
                            Guid = Guid.NewGuid().ToString(),
                            Storage_SN = "000",
                            Area_SN = "0",
                            Location_SN = "0",
                            PartNumber = dr["PartNumber"].ToString(),
                            EnterTime = DateTime.Now,
                            Qty = Convert.ToDecimal(dr["Qty"]),
                            Status = "1",
                            Unit = dr["Unit"].ToString(),
                        };
                        inventoryList.Add(inventory);
                        var inventoryHis = new WMS_T_InventoryHistory()
                        {
                            Guid = Guid.NewGuid().ToString(),
                            Storage_SN = "000",
                            Area_SN = "0",
                            Location_SN = "0",
                            PartNumber = dr["PartNumber"].ToString(),
                            Qty = Convert.ToDecimal(dr["Qty"]),
                            CreateTime = DateTime.Now,
                            Creator = dr["Creator"].ToString(),
                            IO = "I",
                            RelatedBill1 = dr["RelatedBill"].ToString(),
                            RelatedBill2 = dr["BillNO"].ToString()
                        };
                        inventoryHisList.Add(inventoryHis);
                    }
                    new BaseSqlDBDAL<WMS_T_Inventory>().InsertBatch(inventoryList);
                    new BaseSqlDBDAL<WMS_T_InventoryHistory>().InsertBatch(inventoryHisList);
                }

                result = true;
            }
            catch (Exception ex)
            {

            }

            return result;
        }


        public void UpdateInventoryForVMB(List<WMS_T_OutStock> list, List<WMS_T_OutStockRows> rowList)
        {
            WMS_T_InventoryDAL wMS_T_InventoryDAL = new WMS_T_InventoryDAL();

            WMS_T_InventoryHistoryDAL wMS_T_InventoryHistoryDAL = new WMS_T_InventoryHistoryDAL();

            foreach (var item in list)
            {
                var rowsList = rowList.Where(x => x.BillNo.EqualsOrdinalIgnoreCase(item.RelatedBill)).ToList();
                var Storage_SN = item.Storage_SN;

                var isFinish = true;
                foreach (var row in rowsList)
                {
                    var excRes = wMS_T_InventoryDAL.UpdateQty(Storage_SN, row.ProductNumber, row.PlanQty);
                    if (excRes > 0)
                    {
                        row.SelectQty = row.PlanQty;
                        row.RealQty = row.PlanQty;

                        var inventoryHis = new WMS_T_InventoryHistory()
                        {
                            Guid = Guid.NewGuid().ToString(),
                            Storage_SN = Storage_SN,
                            Area_SN = "0",
                            Location_SN = "0",
                            PartNumber = row.ProductNumber,
                            Qty = -row.PlanQty,
                            CreateTime = DateTime.Now,
                            Creator = item.Creator,
                            IO = "O",
                            RelatedBill1 = item.RelatedBill,
                            RelatedBill2 = item.BillNo
                        };
                        wMS_T_InventoryHistoryDAL.Insert(inventoryHis);
                    }
                    else
                    {
                        isFinish = false;
                    }
                    row.BillNo = item.BillNo;

                }
                if (isFinish)
                {
                    item.status = "2";
                }
                else
                {
                    item.status = "E";
                }
            }

        }

        public void SyncInstockRETData(List<WMS_T_OutStock> list, List<WMS_T_OutStockRows> rowList)
        {
            var instockList = new List<WMS_T_InStock>();
            var instockRowsList = new List<WMS_T_InStockRows>();
            foreach (var item in list)
            {
                var instock = new WMS_T_InStock()
                {
                    Guid = Guid.NewGuid().ToString(),
                    BillType = "销售退货",
                    Status = "0",
                    BillNo = item.BillNo,
                    RelatedBill = item.RelatedBill,
                    CreateTime = DateTime.Now,
                    Creator = item.Creator,
                };
                instockList.Add(instock);
            }

            foreach (var item in rowList)
            {
                var instockRow = new WMS_T_InStockRows()
                {
                    Guid = Guid.NewGuid().ToString(),
                    BillNo = item.BillNo,
                    PartNumber = item.ProductNumber,
                    PlanQty = item.PlanQty,
                    RowNo = item.RowNo,
                    Unit = item.Package,
                };
                instockRowsList.Add(instockRow);
            }
            if (instockList.Count > 0)
            {
                new BaseSqlDBDAL<WMS_T_InStock>().InsertBatch(instockList);
            }
            if (instockRowsList.Count > 0)
            {
                new BaseSqlDBDAL<WMS_T_InStockRows>().InsertBatch(instockRowsList);
            }
        }

    }
}
